<template>
  <div class="exception-logs-container">
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="异常类型">
          <el-select
            v-model="searchForm.exception_type"
            placeholder="请选择异常类型"
          >
            <el-option label="全部" value="" />
            <el-option label="系统错误" value="system_error" />
            <el-option label="设备故障" value="device_failure" />
            <el-option label="任务中断" value="task_interruption" />
          </el-select>
        </el-form-item>
        <el-form-item label="异常级别">
          <el-select
            v-model="searchForm.exception_level"
            placeholder="请选择异常级别"
          >
            <el-option label="全部" value="" />
            <el-option label="严重" value="critical" />
            <el-option label="警告" value="warning" />
            <el-option label="信息" value="info" />
          </el-select>
        </el-form-item>
        <el-form-item label="处理状态">
          <el-select v-model="searchForm.status" placeholder="请选择处理状态">
            <el-option label="全部" value="" />
            <el-option label="待处理" value="pending" />
            <el-option label="已解决" value="resolved" />
          </el-select>
        </el-form-item>
        <el-form-item label="无人机ID">
          <el-input
            v-model="searchForm.drone_id"
            placeholder="请输入无人机ID"
          />
        </el-form-item>
        <el-form-item label="任务ID">
          <el-input v-model="searchForm.task_id" placeholder="请输入任务ID" />
        </el-form-item>
        <el-form-item label="责任人">
          <el-input
            v-model="searchForm.responsible_user_id"
            placeholder="请输入责任人ID"
          />
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="searchForm.timeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchExceptionLogs">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="data-card">
      <el-table :data="exceptionLogs" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="exception_type" label="异常类型" width="120">
          <template #default="scope">
            <el-tag
              v-if="scope.row.exception_type === 'system_error'"
              type="danger"
              >系统错误</el-tag
            >
            <el-tag
              v-else-if="scope.row.exception_type === 'device_failure'"
              type="warning"
              >设备故障</el-tag
            >
            <el-tag
              v-else-if="scope.row.exception_type === 'task_interruption'"
              type="info"
              >任务中断</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column prop="exception_level" label="异常级别" width="100">
          <template #default="scope">
            <el-tag
              v-if="scope.row.exception_level === 'critical'"
              type="danger"
              >严重</el-tag
            >
            <el-tag
              v-else-if="scope.row.exception_level === 'warning'"
              type="warning"
              >警告</el-tag
            >
            <el-tag v-else-if="scope.row.exception_level === 'info'" type="info"
              >信息</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column prop="title" label="异常标题" show-overflow-tooltip />
        <el-table-column prop="drone_id" label="无人机ID" width="100" />
        <el-table-column prop="task_id" label="任务ID" width="100" />
        <el-table-column prop="status" label="处理状态" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 'pending'" type="warning"
              >待处理</el-tag
            >
            <el-tag v-else-if="scope.row.status === 'resolved'" type="success"
              >已解决</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column prop="responsible_user" label="责任人" width="120">
          <template #default="scope">
            {{ scope.row.responsible_user?.username || "-" }}
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="发生时间" width="180" />
        <el-table-column prop="resolution_time" label="解决时间" width="180" />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click="handleViewDetail(scope.row)"
              >详情</el-button
            >
            <el-button
              type="primary"
              link
              @click="handleUpdateStatus(scope.row)"
              v-if="scope.row.status === 'pending'"
              >处理</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="异常日志详情"
      width="60%"
      :before-close="handleDetailDialogClose"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="ID">{{
          selectedLog?.id
        }}</el-descriptions-item>
        <el-descriptions-item label="异常类型">
          <el-tag
            v-if="selectedLog?.exception_type === 'system_error'"
            type="danger"
            >系统错误</el-tag
          >
          <el-tag
            v-else-if="selectedLog?.exception_type === 'device_failure'"
            type="warning"
            >设备故障</el-tag
          >
          <el-tag
            v-else-if="selectedLog?.exception_type === 'task_interruption'"
            type="info"
            >任务中断</el-tag
          >
        </el-descriptions-item>
        <el-descriptions-item label="异常级别">
          <el-tag
            v-if="selectedLog?.exception_level === 'critical'"
            type="danger"
            >严重</el-tag
          >
          <el-tag
            v-else-if="selectedLog?.exception_level === 'warning'"
            type="warning"
            >警告</el-tag
          >
          <el-tag
            v-else-if="selectedLog?.exception_level === 'info'"
            type="info"
            >信息</el-tag
          >
        </el-descriptions-item>
        <el-descriptions-item label="标题">{{
          selectedLog?.title
        }}</el-descriptions-item>
        <el-descriptions-item label="详细描述" :span="2">{{
          selectedLog?.description
        }}</el-descriptions-item>
        <el-descriptions-item label="发生位置" :span="2">
          <pre v-if="selectedLog?.location">{{
            JSON.stringify(selectedLog.location, null, 2)
          }}</pre>
          <span v-else>-</span>
        </el-descriptions-item>
        <el-descriptions-item label="无人机ID">{{
          selectedLog?.drone_id || "-"
        }}</el-descriptions-item>
        <el-descriptions-item label="任务ID">{{
          selectedLog?.task_id || "-"
        }}</el-descriptions-item>
        <el-descriptions-item label="检测日志ID">{{
          selectedLog?.detection_log_id || "-"
        }}</el-descriptions-item>

        <el-descriptions-item label="处理状态">
          <el-tag v-if="selectedLog?.status === 'pending'" type="warning"
            >待处理</el-tag
          >
          <el-tag v-else-if="selectedLog?.status === 'resolved'" type="success"
            >已解决</el-tag
          >
        </el-descriptions-item>
        <el-descriptions-item label="责任人">{{
          selectedLog?.responsible_user?.username || "-"
        }}</el-descriptions-item>
        <el-descriptions-item label="解决描述" :span="2">{{
          selectedLog?.resolution_description || "-"
        }}</el-descriptions-item>
        <el-descriptions-item label="发生时间">{{
          selectedLog?.created_at
        }}</el-descriptions-item>
        <el-descriptions-item label="解决时间">{{
          selectedLog?.resolution_time || "-"
        }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{
          selectedLog?.updated_at
        }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 处理对话框 -->
    <el-dialog
      v-model="processDialogVisible"
      title="处理异常"
      width="50%"
      :before-close="handleProcessDialogClose"
    >
      <el-form :model="processForm" ref="processFormRef" label-width="100px">
        <el-form-item label="责任人" prop="responsible_user_id">
          <el-input
            v-model="processForm.responsible_user_id"
            placeholder="请输入责任人ID"
          />
        </el-form-item>
        <el-form-item label="处理状态" prop="status">
          <el-select v-model="processForm.status" placeholder="请选择处理状态">
            <el-option label="待处理" value="pending" />
            <el-option label="已解决" value="resolved" />
          </el-select>
        </el-form-item>
        <el-form-item label="解决描述" prop="resolution_description">
          <el-input
            v-model="processForm.resolution_description"
            type="textarea"
            :rows="4"
            placeholder="请输入解决描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="processDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitProcess">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import service from "@/utils/request.js";

export default {
  name: "ExceptionLogs",
  setup() {
    const loading = ref(false);
    const exceptionLogs = ref([]);
    const detailDialogVisible = ref(false);
    const processDialogVisible = ref(false);
    const selectedLog = ref(null);
    const processFormRef = ref(null);

    const searchForm = reactive({
      exception_type: "",
      exception_level: "",
      status: "",
      drone_id: "",
      task_id: "",
      responsible_user_id: "",
      timeRange: [],
    });

    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0,
    });

    const processForm = reactive({
      responsible_user_id: "",
      status: "pending",
      resolution_description: "",
    });

    const fetchExceptionLogs = async () => {
      loading.value = true;
      try {
        const params = {
          skip: (pagination.currentPage - 1) * pagination.pageSize,
          limit: pagination.pageSize,
          exception_type: searchForm.exception_type || undefined,
          exception_level: searchForm.exception_level || undefined,
          status: searchForm.status || undefined,
          drone_id: searchForm.drone_id
            ? parseInt(searchForm.drone_id)
            : undefined,
          task_id: searchForm.task_id
            ? parseInt(searchForm.task_id)
            : undefined,
          responsible_user_id: searchForm.responsible_user_id
            ? parseInt(searchForm.responsible_user_id)
            : undefined,
        };

        if (searchForm.timeRange && searchForm.timeRange.length === 2) {
          params.start_time = searchForm.timeRange[0];
          params.end_time = searchForm.timeRange[1];
        }

        const response = await service.get("/exception-logs", { params });
        exceptionLogs.value = response.data;
        pagination.total = response.total;
      } catch (error) {
        ElMessage.error(
          "获取异常日志失败: " +
            (error.response?.data?.message || error.message)
        );
      } finally {
        loading.value = false;
      }
    };

    const resetSearch = () => {
      Object.keys(searchForm).forEach((key) => {
        if (Array.isArray(searchForm[key])) {
          searchForm[key] = [];
        } else {
          searchForm[key] = "";
        }
      });
      pagination.currentPage = 1;
      fetchExceptionLogs();
    };

    const handleSizeChange = (size) => {
      pagination.pageSize = size;
      pagination.currentPage = 1;
      fetchExceptionLogs();
    };

    const handleCurrentChange = (current) => {
      pagination.currentPage = current;
      fetchExceptionLogs();
    };

    const handleViewDetail = (log) => {
      selectedLog.value = log;
      detailDialogVisible.value = true;
    };

    const handleDetailDialogClose = () => {
      selectedLog.value = null;
      detailDialogVisible.value = false;
    };

    const handleUpdateStatus = (log) => {
      selectedLog.value = log;
      processForm.responsible_user_id = log.responsible_user_id || "";
      processForm.status = log.status;
      processForm.resolution_description = log.resolution_description || "";
      processDialogVisible.value = true;
    };

    const handleProcessDialogClose = () => {
      processDialogVisible.value = false;
      if (processFormRef.value) {
        processFormRef.value.resetFields();
      }
    };

    const submitProcess = async () => {
      try {
        const response = await service.put(
          `/exception-logs/${selectedLog.value.id}`,
          {
            responsible_user_id: processForm.responsible_user_id
              ? parseInt(processForm.responsible_user_id)
              : null,
            status: processForm.status,
            resolution_description: processForm.resolution_description,
          }
        );
        ElMessage.success("处理成功");
        processDialogVisible.value = false;
        fetchExceptionLogs();
      } catch (error) {
        ElMessage.error(
          "处理失败: " + (error.response?.data?.message || error.message)
        );
      }
    };

    onMounted(() => {
      fetchExceptionLogs();
    });

    return {
      loading,
      exceptionLogs,
      searchForm,
      pagination,
      detailDialogVisible,
      processDialogVisible,
      selectedLog,
      processForm,
      processFormRef,
      fetchExceptionLogs,
      resetSearch,
      handleSizeChange,
      handleCurrentChange,
      handleViewDetail,
      handleDetailDialogClose,
      handleUpdateStatus,
      handleProcessDialogClose,
      submitProcess,
    };
  },
};
</script>

<style scoped>
.exception-logs-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  margin: 0;
}

.data-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
